/**
 * 作者：风雪涟漪 版本0.3v 上次更新：2009-11-20 更新： 1.增加自定义排序 2.增加日期的选中 3.代码的重构
 */

( function($) {

	jQuery.fn.datecontrol = function(options) {
		var defaults = {
			startdate :new Date(),
			enddate :new Date(),
			format :"mm/dd/yyyy",
			word : {
				define :"自定义时间范围",
				today :"今天",
				yestoday :"昨天",
				lastweek :"上周",
				month :"这个月",
				lastmonth :"上个月",
				apply :"应用"
			},
			dateDisplay : [ 'define', 'today', 'yestoday', 'lastweek', 'month',
					'lastmonth' ],// 定义显示数据
			hiddenStartName :'startdate',
			hiddenEndName :'enddate',
			onApply : function(value, date) {
			}
		}

		var options = $.extend(defaults, options);

		return this
				.each( function() {
					var i = Math.floor(Math.random() * 1000 + 1);

					var o = options;
					var startDate = o.startdate;
					var endDate = o.enddate;

					var idDateView = 'id_date_view' + i;
					var idDateContent = 'id_date_content' + i;
					var idLastMonth = 'id_last_month' + i;
					var idMonth = 'id_month' + i;
					var idLastWeek = 'id_last_week' + i;
					var idYestoday = 'id_yestoday' + i;
					var idToday = 'id_today' + i;
					var idDefine = 'id_define' + i;
					var idApply = 'id_apply' + i;
					var idDefineInput = "id_define_input" + i;
					var idHiddenStart = "id_hidden_start" + i;
					var idHiddenEnd = "id_hidden_end" + i;

					var dateliDefine = "<li  class='li_content'><input id="
							+ idDefine + " name='selectdate" + i
							+ "' type='radio'></input><span id="
							+ idDefineInput + ">" + o.word.define
							+ "</span></li>";
					var dateliToday = "<li class='li_content'><input id="
							+ idToday + " name='selectdate" + i
							+ "' type='radio'></input>" + o.word.today
							+ "</li>";
					var dateliYestoday = "<li class='li_content'><input id="
							+ idYestoday + " name='selectdate" + i
							+ "' type='radio'></input>" + o.word.yestoday
							+ "</li>";

					var dateliLastweek = "<li class='li_content'><input id="
							+ idLastWeek + " name='selectdate" + i
							+ "' type='radio'></input>" + o.word.lastweek
							+ "</li>";

					var dateliMonth = "<li class='li_content'><input id="
							+ idMonth + " name='selectdate" + i
							+ "' type='radio'></input>" + o.word.month
							+ "</li>";

					var deteliLastmonth = "<li class='li_content'><input id="
							+ idLastMonth + " name='selectdate" + i
							+ "' type='radio'></input>" + o.word.lastmonth
							+ "</li>";

					var lisubmit = "<li class='li_content'><input id="
							+ idApply + " class='btn_b' type='button' value='"
							+ o.word.apply + "'></input></li>";
					var licontent = displayDateByOrder(o.dateDisplay) ;
					licontent+= lisubmit;
					var ulcontent = "<ul id=" + idDateContent
							+ " class='ul_content'>";
					var divdate = "<div id=" + idDateView
							+ " class='view_date'></div>";

					var divdatecontrol = "<div class='date_container'>";
					// alert(idHiddenStart+idHiddenEnd+hiddenStartName+hiddenEndName+"");
					var hiddenText = "<input id='" + idHiddenStart
							+ "' type='hidden' name='" + o.hiddenStartName
							+ "'/>" + "<input id='" + idHiddenEnd
							+ "' type='hidden' name='" + o.hiddenEndName
							+ "'/>";
					// alert(hiddenText);
					var finalHtml = "<div class='date_container'>" + divdate
							+ ulcontent + licontent + hiddenText
							+ "</ul></div>";
					$(this).html(finalHtml);
					// init
					selectDate(o.startdate, o.enddate);
					showDisplay(o.startdate, o.enddate);

					$("#" + idDateView).click( function() {
						$("#" + idDateContent).slideToggle('fast');
					});
					// 获取上个月的范围
					$("#" + idLastMonth).click( function() {
						startDate = getLastMonthStart();
						endDate = getMonthEnd(getLastMonthStart());
						showDisplay(startDate, endDate);
						$("#" + idDefineInput).html(o.word.define);$("#" + idApply).click();
					})

					// 获取这个月的范围
					$("#" + idMonth).click( function() {
						startDate = getMonthStart();
						endDate = getMonthEnd(getMonthStart());
						showDisplay(startDate, endDate);
						$("#" + idDefineInput).html(o.word.define);$("#" + idApply).click();
					});

					// 获取上周的范围
					$("#" + idLastWeek).click( function() {
						startDate = getLastWeekStart();
						endDate = getLastWeekEnd(getLastWeekStart());
						showDisplay(startDate, endDate);
						$("#" + idDefineInput).html(o.word.define);$("#" + idApply).click();
					});
					// 获取昨天的范围
					$("#" + idYestoday).click( function() {
						startDate = getYestoday();
						endDate = getYestoday();
						showDisplay(startDate, endDate);
						$("#" + idDefineInput).html(o.word.define);
						$("#" + idApply).click();
					});
					// 获取今天的范围
					$("#" + idToday).click( function() {
						startDate = new Date();
						endDate = new Date();
						showDisplay(startDate, endDate);
						$("#" + idDefineInput).html(o.word.define);
						$("#" + idApply).click();
					});

					$("#" + idDefine)
							.click(
									function() {
										
										var idDatePicker = "id_datepicker" + i;
										$("#" + idDefineInput)
												.html(
														"<input type='text' id="
																+ idDatePicker
																+ " class='definedate'></input>");
										$("#" + idDatePicker)
												.val(
														startDate
																.format(o.format)
																+ " - "
																+ endDate
																		.format(o.format));
										var dateFormat = o.format;

										if (getCharNumber(o.format, "y") == 4) {
											dateFormat = o.format.replace(
													"yyyy", "yy");
										} else if (getCharNumber(o.format, "y") == 2) {
											dateFormat = o.format.replace("yy",
													"y");
										}
										var alld=1;

										$(".definedate").datepick(
												{
													autoSize :true,
													dateFormat :dateFormat,
													rangeSelect :true,
													numberOfMonths :2,
													buttonImageOnly :true,
													onSelect : function(value,
															date) {
														startDate = date[0];
														endDate = date[1];
														$("#" + idDateView)
																.html(value);alld++;
														if(alld%2==1 && alld!=1)
															$("#" + idApply).click();
														// $(".definedate").val(value.split("-")[1]);
														// $(".definedate").val($("#startdate").val()+"-"+$("#enddate").val());
													}
												});

									});

					$("#" + idApply).click(
							function() {
								$("#" + idDateContent).slideUp('fast');
								var value = new Array(startDate
										.format(o.format), endDate
										.format(o.format));
								var date = new Array(startDate, endDate);
								o.onApply(value, date);
								showDisplay1(value);
							});


					
					function showDisplay(startdate, enddate) {

						$("#" + idDateView).html(
								startdate.format(o.format) + " - "
										+ enddate.format(o.format));
						$("#" + idHiddenStart).val(startdate.format(o.format));
						$("#" + idHiddenEnd).val(enddate.format(o.format));
					}

					function showDisplay1(vh) {
						$("#" + idHiddenStart).val(vh[0]);
						$("#" + idHiddenEnd).val(vh[1]);
					}

					function displayDateByOrder(arrayDate) {
						var i;
						var finalDateli="";
						for (i = 0; i < arrayDate.length; i++) {
							finalDateli+=getDateLi(arrayDate[i]);
						}
						return finalDateli;
					}

					/**
					 * 获取日期选项的单项
					 */
					function getDateLi(dateName) {
						
						switch (dateName) {
						case 'define':
							return dateliDefine;
						case 'today':
							return dateliToday;
						case 'yestoday':
							return dateliYestoday;
						case 'lastweek':
							return dateliLastweek;
						case 'month':
							return dateliMonth;
						case 'lastmonth':
							return deteliLastmonth;
						}
					}
					/**
					 * 选中日期
					 */
					function selectDate(start,end){
						var formatStart = start.format(o.format);
						var formatEnd = end.format(o.format);
						if(formatStart==getYestoday().format(o.format)&&formatEnd==getYestoday().format(o.format)){
							$("#" + idYestoday).attr("checked",true);
						}else if(formatStart==new Date().format(o.format)&&formatEnd==new Date().format(o.format)){
							$("#" + idToday).attr("checked",true);
						}else if(formatStart==getLastWeekStart().format(o.format)&&formatEnd==getLastWeekEnd(getLastWeekStart()).format(o.format)){
							$("#" + idLastWeek).attr("checked",true);
						}else if(formatStart==getMonthStart().format(o.format)&&formatEnd==getMonthEnd(getMonthStart()).format(o.format)){
							$("#" + idMonth).attr("checked",true);
						}else if(formatStart==getLastMonthStart().format(o.format)&&formatEnd==getMonthEnd(getLastMonthStart()).format(o.format)){
							$("#" + idLastMonth).attr("checked",true);
						}else{
							$("#" + idDefine).attr("checked",true);
							clickDefine();
						}
						$("#" + idHiddenStart).val(formatStart);
						$("#" + idHiddenEnd).val(formatEnd);
						
					}
					
					/**
					 * 点击自定义事件
					 */
					function clickDefine(){
						
						var idDatePicker = "id_datepicker" + i;
						$("#" + idDefineInput)
								.html(
										"<input type='text' id="
												+ idDatePicker
												+ " class='definedate'></input>");
						$("#" + idDatePicker)
								.val(
										startDate
												.format(o.format)
												+ " - "
												+ endDate
														.format(o.format));
						var dateFormat = o.format;

						if (getCharNumber(o.format, "y") == 4) {
							dateFormat = o.format.replace(
									"yyyy", "yy");
						} else if (getCharNumber(o.format, "y") == 2) {
							dateFormat = o.format.replace("yy",
									"y");
						}

						$(".definedate").datepick(
								{
									autoSize :true,
									dateFormat :dateFormat,
									rangeSelect :true,
									numberOfMonths :2,
									buttonImageOnly :true,
									onSelect : function(value,
											date) {
										startDate = date[0];
										endDate = date[1];
										$("#" + idDateView)
												.html(value);
										
										// $(".definedate").val(value.split("-")[1]);
										// $(".definedate").val($("#startdate").val()+"-"+$("#enddate").val());
									}
								});
					}

				});

	};
	function getCharNumber(source, charSet) {
		var i;
		var count = 0;
		for (i = 0; i < source.length; i++) {
			// alert(source[i]);
			if (source.charAt(i) == charSet) {

				count = count + 1;
			}
		}
		return count;
	}

	/**
	 * 获取昨天的日期
	 * 
	 * @return
	 */
	function getYestoday() {
		var dt = new Date();
		dt.setDate(dt.getDate() - 1);

		return dt
	}

	/**
	 * 上一周的开始日期
	 * 
	 * @return
	 */
	function getLastWeekStart() {
		var lastWeekStart = new Date();
		if (lastWeekStart.getDay() == 0) {
			lastWeekStart.setDate(lastWeekStart.getDate()
					- lastWeekStart.getDay() - 13);

		} else {
			lastWeekStart.setDate(lastWeekStart.getDate()
					- lastWeekStart.getDay() - 6);
		}
		return lastWeekStart;
	}

	function getLastWeekEnd(lastWeekStart) {
		lastWeekStart.setDate(lastWeekStart.getDate() + 6);
		return lastWeekStart;
	}

	/**
	 * 获取本月的开始日期
	 * 
	 * @return
	 */
	function getMonthStart() {
		var monthStart = new Date();
		monthStart.setDate(1);
		return monthStart;
	}

	/**
	 * 获取上月的开始日期
	 * 
	 * @return
	 */
	function getLastMonthStart() {
		var lastMonthStart = new Date();
		lastMonthStart.setMonth(lastMonthStart.getMonth() - 1, 1);
		return lastMonthStart;
	}
	/**
	 * 获取月末日期
	 */
	function getMonthEnd(monthDate) {
		var lastMonthDay = new Date(monthDate.getFullYear(), monthDate
				.getMonth() + 1, 0);
		return lastMonthDay;
	}

	/**
	 * Date format
	 * 
	 * var now = new Date();
	 * 
	 * now.format("m/dd/yy"); // Returns, e.g., 6/09/07 // Can also be used as a
	 * standalone function dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"); //
	 * Saturday, June 9th, 2007, 5:46:21 PM // You can use one of several named
	 * masks now.format("isoDateTime"); // 2007-06-09T17:46:21 // ...Or add your
	 * own dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
	 * now.format("hammerTime"); // 17:46! Can't touch this! // When using the
	 * standalone dateFormat function, // you can also provide the date as a
	 * string dateFormat("Jun 9 2007", "fullDate"); // Saturday, June 9, 2007 //
	 * Note that if you don't include the mask argument, //
	 * dateFormat.masks.default is used now.format(); // Sat Jun 09 2007
	 * 17:46:21 // And if you don't include the date argument, // the current
	 * date and time is used dateFormat(); // Sat Jun 09 2007 17:46:22 // You
	 * can also skip the date argument (as long as your mask doesn't // contain
	 * any numbers), in which case the current date/time is used
	 * dateFormat("longTime"); // 5:46:22 PM EST // And finally, you can convert
	 * local time to UTC time. Either pass in // true as an additional argument
	 * (no argument skipping allowed in this case): dateFormat(now, "longTime",
	 * true); now.format("longTime", true); // Both lines return, e.g., 10:46:21
	 * PM UTC // ...Or add the prefix "UTC:" to your mask.
	 * now.format("UTC:h:MM:ss TT Z"); // 10:46:21 PM UTC
	 */
	var dateFormat = function() {
		var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(
				val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len)
				val = "0" + val;
			return val;
		};

		// Regexes and supporting functions are cached through closure
		return function(date, mask, utc) {
			var dF = dateFormat;

			// You can't provide utc if you skip other args (use the "UTC:" mask
			// prefix)
			if (arguments.length == 1
					&& Object.prototype.toString.call(date) == "[object String]"
					&& !/\d/.test(date)) {
				mask = date;
				date = undefined;
			}

			// Passing date through Date applies Date.parse, if necessary
			date = date ? new Date(date) : new Date;
			if (isNaN(date))
				throw SyntaxError("invalid date");

			mask = String(dF.masks[mask] || mask || dF.masks["default"]);

			// Allow setting the utc argument via the mask
			if (mask.slice(0, 4) == "UTC:") {
				mask = mask.slice(4);
				utc = true;
			}

			var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_
					+ "Day"](), m = date[_ + "Month"](), y = date[_
					+ "FullYear"](), H = date[_ + "Hours"](), M = date[_
					+ "Minutes"](), s = date[_ + "Seconds"](), L = date[_
					+ "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = {
				d :d,
				dd :pad(d),
				ddd :dF.i18n.dayNames[D],
				dddd :dF.i18n.dayNames[D + 7],
				m :m + 1,
				mm :pad(m + 1),
				mmm :dF.i18n.monthNames[m],
				mmmm :dF.i18n.monthNames[m + 12],
				yy :String(y).slice(2),
				yyyy :y,
				h :H % 12 || 12,
				hh :pad(H % 12 || 12),
				H :H,
				HH :pad(H),
				M :M,
				MM :pad(M),
				s :s,
				ss :pad(s),
				l :pad(L, 3),
				L :pad(L > 99 ? Math.round(L / 10) : L),
				t :H < 12 ? "a" : "p",
				tt :H < 12 ? "am" : "pm",
				T :H < 12 ? "A" : "P",
				TT :H < 12 ? "AM" : "PM",
				Z :utc ? "UTC" : (String(date).match(timezone) || [ "" ]).pop()
						.replace(timezoneClip, ""),
				o :(o > 0 ? "-" : "+")
						+ pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o)
								% 60, 4),
				S : [ "th", "st", "nd", "rd" ][d % 10 > 3 ? 0 : (d % 100 - d
						% 10 != 10)
						* d % 10]
			};

			return mask.replace(token, function($0) {
				return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
			});
		};
	}();

	// Some common format strings
	dateFormat.masks = {
		"default" :"ddd mmm dd yyyy HH:MM:ss",
		shortDate :"m/d/yy",
		mediumDate :"mmm d, yyyy",
		longDate :"mmmm d, yyyy",
		fullDate :"dddd, mmmm d, yyyy",
		shortTime :"h:MM TT",
		mediumTime :"h:MM:ss TT",
		longTime :"h:MM:ss TT Z",
		isoDate :"yyyy-mm-dd",
		isoTime :"HH:MM:ss",
		isoDateTime :"yyyy-mm-dd'T'HH:MM:ss",
		isoUtcDateTime :"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
	};

	// Internationalization strings
	dateFormat.i18n = {
		dayNames : [ "日", "一", "二", "三", "四", "五", "六", "星期天",
				"星期一", "星期二", "星期三", "星期四", "星期五",
				"星期六" ],
		monthNames : [ "一", "二", "三", "四", "五", "六", "七", "八",
				"九", "十", "十一", "十二", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月",
				"九月", "十月", "十一月", "十二月" ]
	};

	// For convenience...
	Date.prototype.format = function(mask, utc) {
		return dateFormat(this, mask, utc);
	};
})(jQuery);

;(function($){
	$.fn.extend({
		"addinput":function(o){ //动态增加input
			o = $.extend({
				clicker : 	"", //开关，点击增加，可以根据class选择，默认.next()获取
				wrap : 		"li", //input的父标签
				name : 		"i-text", //input的name
				type : 		"text", //input的type
				maxlength : 20, //input的maxlength
				className : "", //input的class
				inputMax : 	0 , //新增input的上限，0表示不限制
				delClassName : "remove" //删除按钮的样式
			},o);
			//补全input的父标签
			var wrapStart = "<"+ o.wrap +">", wrapEnd = "</"+ o.wrap +">";
			//input的代码
			var input = "<input type='"+ o.type +"' name='"+ o.name +"' maxlength='"+ o.maxlength +"'"+ (!o.className ? "" : " class='"+ o.className +"'") +" />";
			var remove = "<a href='#nogo' class='"+o.delClassName+"'>移除</a>";
			var content = wrapStart + input + remove + wrapEnd;
			//定义一个变量，把容器赋值给它（因为会多次使用）
			var $container = this;
			//初始增加一个input，没有“移除”按钮
			$container.append(wrapStart + input + wrapEnd);
			
			var len;
			//增加input
			var $Ctrl = !o.clicker ? $container.next() : $(o.clicker);
			$Ctrl.bind("click", function(){
				var $item = $container.children(o.wrap);
				len = $item.length;//未增加前的input个数
				//设置一个开关，当开关为TRUE时才允许增加
				var isMax = o.inputMax==0 ? false : (len<o.inputMax ? false : true);
				if(!isMax){
					$(content).appendTo($container).find("."+o.delClassName).click(function(){
						$(this).parent().remove();//移除当前input
						len = $container.children(o.wrap).length; //统计剩下的个数
						if(len==1) {
							$container.find("."+o.delClassName).remove(); //只剩一个的时候，把“移除”按钮干掉
						}
						return false;
					});
					if(len==1) {
						$(remove).appendTo( $item ).click(function(){
							$(this).parent().remove();//移除当前input
							len = $container.children(o.wrap).length; //统计剩下的个数
							if(len==1) {
								$container.find("."+o.delClassName).remove(); //只剩一个的时候，把“移除”按钮干掉
							}
							return false;
						});//此时的len还是未增加前的input个数，增加第二个的时候的同时，为第一个input增加“移除”按钮。放在此处，可以防止inputMax为负数等情况的错误
					}
				}
				return false;
			});
		}
	});
})(jQuery);

